define(['jquery','cookie'], function () {
  class Header {
    constructor() {
      this.loadHTML().then(() => {
        this.search();
        this.isCookie();
        this.calcCartCount ()
      })

    }
    loadHTML() {
      // 加载头部HTML
      return new Promise(resolve => {
        $('header').load('/html/modules/header.html', resolve);
      })

    }
    search() {
      // 头部搜索框
      $('.header-bottom-search input').on('keyup', function () {
        const wd = $(this).val()
        $.getJSON('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?cb=?', { wd }, resp => {
        })
      })
    }
    // 购物车渲染页面
    calcCartCount () {
      let totalCount = 0
      // 取出localStorage的数据，计算总数量
      let cart = localStorage.getItem('cart')
      if (cart) {
        cart = JSON.parse(cart)
        totalCount = cart.reduce((count, shop) => {
          count += shop.count
          return count
        }, 0)
      }
      $('#cartnum, .text p').html(totalCount)
    }

 //判断cookie的值
    //有值得话就显示用户名，并让盒子显示
    isCookie () {
     
      let dataname = $.cookie('dataname')
      console.log(dataname)
      if (dataname) {
          $('#un-login').css('display','none')
          $('#reg-btn').css('display','none')
          $('#is-login').css('display','block')
          $('#logout-btn').css('display','block')
          $('#username').css('display','block')
          $('#username').html(dataname)
      }
  //当点击退出的时候删除全局的cookie。让盒子消失  
      $('#logout-btn').on('click', function () {
          if (confirm('你确定要退出吗')) {
              $.removeCookie('dataname', { path: '/html' })
              $.removeCookie('dataname', { path: '/' })
              $('#un-login').css('display','block')
              $('#reg-btn').css('display','block')
              $('#is-login').css('display','none')
              $('#logout-btn').css('display','none')
              $('#username').css('display','none')
              $('#username').html('')
          }
      })


  }


  }
  return new Header()
});